﻿using System;
using System.Collections.Generic;
using System.IO;
using Zove.Query;
using FunctionalCLR.Shell;
using Zove.Shell.Core;
using FunctionalCLR.Core;
using FunctionalCLR.Core.Logging;
using FunctionalCLR.Core.Function;
using FunctionalCLR.Shell.Function.IO;

namespace Zove.Interactive {
    class Program {
        static void Main(string[] args) {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Title = "Zove Workbench";
            Console.WriteLine("Zove Workbench for Common Language Runtime\nCopyright Zove System 2009\n");

            if (args.Length == 0) {
                Console.Write("> ");

                ZoveShellInterpreter intp
                    = new ZoveShellInterpreter();
                while (true) {
                    try {
                        string stmt = Console.ReadLine().Trim();
                        object result = intp.Process(stmt);
                        Console.WriteLine("< {0}", Convert.ToString(result));
                    } catch (TerminateException te) {
                        Console.WriteLine("Quiting program...");
                        break;
                    } catch(ClearScreenException cse) {
                        Console.Clear();
                    } catch (Exception ex) {
                        Console.WriteLine(ex.Message);
                    }
                    Console.Write("> ");
                }

                return;
            }

            string fileName = args[0];
            if (!File.Exists(fileName)) {
                Console.WriteLine("Cannot find file");
                return;
            }

            try {
                string source = File.ReadAllText(fileName);
                if (fileName.EndsWith(".zql")) {
                    QueryManager qm = new QueryManager();
                    Query.Query query = qm.CreateQuery(source);
                    List<QueryResult> results = query.Run();

                    Console.WriteLine("Result:");
                    foreach (QueryResult r in results) {
                        Console.WriteLine(r);
                    }
                } else if (fileName.EndsWith(".fpz")) {
                    string[] p = new string[args.Length - 1];
                    for (int index = 0; index < args.Length - 1; index++) {
                        p[index] = args[index + 1];
                    }

                    ZoveShellInterpreter intp
                        = new ZoveShellInterpreter();
                    intp.Execute(source, p);
                } else {
                    Console.WriteLine("Unknown file type.");
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                ILogger logger = new EventLogger("Zove");
                logger.WriteLog(ex);
            }
        }
    }
}
